package com.tuzhi.auth.sys.web.controller;

import com.tuzhi.auth.sys.dto.SysMenuTreeDto;
import com.tuzhi.auth.sys.jpa.entity.SysRoleEntity;
import com.tuzhi.auth.sys.jpa.entity.SysUserEntity;
import com.tuzhi.auth.sys.scurity.AuthService;
import com.tuzhi.auth.sys.service.SysRoleService;
import com.tuzhi.base.web.helper.AjaxResultHelper;
import com.tuzhi.common.domain.LoginUserBO;
import com.tuzhi.common.domain.ResultBO;
import com.tuzhi.common.exception.BusinessException;
import com.tuzhi.common.helper.ResultHelper;
import com.tuzhi.util.UserContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/sys/perm")
@Api(tags = "授权")
@Slf4j
@RequiredArgsConstructor
public class SysPermController {
    @Autowired
    AuthService authService;

    private final SysRoleService sysRoleService;


    @ApiOperation("查找完整的菜单树，并标记角色权限")
    @GetMapping("/loadRoleMenuTree/{roleId}")
    public ResultBO<List<SysMenuTreeDto>> loadRoleMenuTree(@PathVariable("roleId") Long roleId) {
//        List<SysMenuTreeDto> menuTreeDtos = authService.loadAllMenuTree4Role(roleId);
        LoginUserBO curLoginUser = UserContext.getUserInfo(true);
        List<SysMenuTreeDto> menuTreeDtos = authService.loadAllMenuTree4RoleBaseOpUser(roleId, curLoginUser.getUserId());
        return ResultHelper.success().ofData(menuTreeDtos);
    }

    @ApiOperation("查找用户有权限的菜单树")
    @GetMapping("/loadUserMenuTree/")
    public ResultBO<List<SysMenuTreeDto>> loadUserMenuTree() {
        LoginUserBO curLoginUser = UserContext.getUserInfo(true);
        List<SysMenuTreeDto> menuTreeDtos = authService.loadUserMenuTree(curLoginUser.getUserId());
        return ResultHelper.success().ofData(menuTreeDtos);
    }

    @ApiOperation("查找当前用户所有的角色列表")
    @GetMapping("/getCurUserRoleName/")
    public ResultBO<List<String>> getCurUserRoleName() {
        LoginUserBO curLoginUser = UserContext.getUserInfo(true);
        List<String> roleNames = authService.loadRoleNames(curLoginUser.getUserId());
        return ResultHelper.success().ofData(roleNames);
    }

    @ApiOperation("保存角色的权限菜单")
    @PostMapping("/savePerms4Role/{roleId}")
    public ResultBO savePerms4Role(@PathVariable("roleId") Long roleId, @RequestBody List<Long> menuIds) {
        authService.savePerms4Role(roleId, menuIds);
        return ResultHelper.success();
    }

    //TODO 保存角色的权限菜单
    @ApiOperation("保存角色的权限菜单sys_auth")
    @PostMapping("/saveRoleAuth")
    public ResultBO saveRoleAuth(@PathVariable("roleId") Long roleId, @RequestBody List<Long> menuIds){
        authService.saveRoleAuth(roleId,menuIds);
        return ResultHelper.success();
    }

    @ApiOperation("保存用户到角色")
    @PostMapping("/saveUserRole/{userId}")
    public ResultBO saveUserRole(@PathVariable("userId") Long userId, @RequestBody List<Long> roleIds) {
        authService.saveUserRole(userId, roleIds);
        return ResultHelper.success();
    }


    @ApiOperation("保存/修改用户信息，如果是修改把用户ID带上")
    @PutMapping({"/saveUser"})
    public ResultBO saveUser(@RequestBody SysUserEntity entity) {
        if (entity == null) {
            throw new BusinessException("参数不能为空");
        }
        if (StringUtils.isBlank(entity.getUsername())) {
            throw new BusinessException("登录帐号不能为空");
        }
        if (StringUtils.isBlank(entity.getNickname())) {
            throw new BusinessException("用户名不能为空");
        }
        if (entity.getOrgId() == null) {
            throw new BusinessException("组织不能为空");
        }
        //解密密码
//        if(!StringUtils.isBlank(entity.getPassword())){
//            Map<String, String> publicKeyAndPrivateKey = rsaEncipherUtil.getPublicKeyAndPrivateKey();
//            String privateKeyStr = publicKeyAndPrivateKey.get(RsaEncipherUtil.PRIVATE_KEY_STR);
//            String pwd = RsaEncipherUtil.decryptByPrivateKey(entity.getPassword(), privateKeyStr);
//            entity.setPassword(pwd);
//        }
        //判断用户是否有权限更改角色
        LoginUserBO userInfo = UserContext.getUserInfo(true);
        if (!(entity.getRoles().isEmpty()) || authService.superAdmin(userInfo.getUserId())) {
            //判断用户是否有权限更改角色
            //1.1获取角色申请列表中最大角色优先级
            List<SysRoleEntity> requireRolesList = sysRoleService.getRoles(new ArrayList(entity.getRoles()));
            Integer requireMaxpriority = Optional.ofNullable(requireRolesList).orElse(new ArrayList<>()).stream()
                    .min(Comparator.comparing(SysRoleEntity::getPriority)).map(SysRoleEntity::getPriority).get();
            //1.2获取用户当前最大角色优先级
            Map maxPriorityRole = sysRoleService.getMaxPriorityRole(userInfo.getUserId());
            //1.3比较优先级
            if (requireMaxpriority != null && (!CollectionUtils.isEmpty(maxPriorityRole))){
                if((Integer) maxPriorityRole.get("priority") > requireMaxpriority){
                    throw new BusinessException("没有权限设置该角色");
                }
            }else {
                throw new BusinessException("没有权限设置该角色");
            }
        }
        authService.saveUserAndRole(entity);
        return AjaxResultHelper.success();
    }

    /**
     * 判断是否系统管理员
     *
     * @param userId
     * @return
     */
    @ApiOperation("是否系统管理员")
    @PostMapping("/superAdmin")
    public ResultBO<Boolean> superAdmin(@RequestParam Long userId) {
        Boolean isAdmin = authService.superAdmin(userId);
        return ResultHelper.success().ofData(isAdmin);
    }

    /**
     * 判断是否企业管理员
     *
     * @param userId
     * @return
     */
    @ApiOperation("是否企业管理员")
    @PostMapping("/enterpriseAdmin")
    public ResultBO<Boolean> enterpriseAdmin(@RequestParam Long userId) {
        Boolean isAdmin = authService.enterpriseAdmin(userId);
        return ResultHelper.success().ofData(isAdmin);
    }


}
